<template>
  <el-dialog @close="close" :title="title" :visible.sync="showDialog">
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item label="角色名称" :label-width="formLabelWidth" prop="name">
        <el-input v-model="form.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item
        label="角色描述"
        :label-width="formLabelWidth"
        prop="description"
      >
        <el-input v-model="form.description" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addRole, editRole } from '@/api/roles'
export default {
  data () {
    return {
      showDialog: false,
      formLabelWidth: '100px',
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async save () {
      try {
        // 做整个表单校验
        await this.$refs.form.validate()
        // 判断是修改还是新增
        if (this.form.id) {
          // 证明是修改
          await editRole(this.form)
          this.$message.success('修改角色成功')
        } else {
          // 发请求
          await addRole(this.form)
          // 弹出成功
          this.$message.success('新增角色成功')
          // 算出最后一页
          this.$parent.total++
          this.$parent.page = Math.ceil(this.$parent.total / this.$parent.size)
        }
        // 刷新父组件数据
        this.$parent.loadData()
        // 把自己隐藏
        this.showDialog = false
      } catch {}
    },
    close () {
      // 重置为初始状态，而修改的初始状态，就是默认查出来的那些值
      // 为了修改关闭时也能清空内容，我们就要手动给form改成默认值
      this.form = {
        name: '',
        description: ''
      }
      this.$refs.form.resetFields()
    }
  },

  computed: {
    title () {
      return this.form.id ? '修改角色' : '新增角色'
    }
  }
}
</script>

<style></style>
